package com.ruoyi.business.component.mqconsumer;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.component.mqconsumer.repaymentconsumers.IRepaymentMqService;
import com.ruoyi.business.component.mqconsumer.repaymentconsumers.RepaymentMqFactory;
import com.ruoyi.common.config.RocketMqTopics;
import com.ruoyi.common.utils.FeishuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消费类型区分消费方法
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumers.repaymentConsumers}", topic = "${rocketmq.consumer-topics.repaymentTopic}",
        messageModel = MessageModel.CLUSTERING,
        consumeMode = ConsumeMode.ORDERLY,
        consumeTimeout = 300L)
public class RepayMentMqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    RepaymentMqFactory repaymentMqFactory;

    @Override
    public void onMessage(MessageExt messageExt) {
        String messageId = messageExt.getMsgId();
        log.info("还款 MQ 开始消费，第 {} 次 >>> messageId = {}", messageExt.getReconsumeTimes(), messageId);

        JSONObject data = JSONObject.parseObject(new String(messageExt.getBody()));
        log.info("还款 MQ，messageId = {}, messageBody = {}", messageId, data);

        String custNo = data.get("custNo").toString();
        String type = data.getString("type");
        JSONObject msgObj = data.getJSONObject("msgObj");
        try {
            log.info("还款 MQ 消费开始 >>> custNo = {}, type = {}, messageId = {}, messageBody = {}", custNo, type, messageId, msgObj.toString());
            // 工厂方式处理不同类型的MQ消息
            IRepaymentMqService repaymentMqService = repaymentMqFactory.getHandle(type);
            repaymentMqService.handle(msgObj);
        } catch (Exception e) {
            // 发送监控
            log.error("还款 MQ 的消费 error：custNo = {}，messageId = {}", custNo, messageId, e);
            FeishuUtils.sendFeishuToMonit(type + "." + custNo, "MQ 消费者-还款", custNo, msgObj.toString(), e);
            throw new RuntimeException(e);
        }
        log.info("还款 MQ 消费结束 >>> custNo = {}，messageId = {}", custNo, messageId);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 设置最大重试次数
        consumer.setMaxReconsumeTimes(RocketMqTopics.getMaxReconsumeTimes());
        // 如下，设置其它consumer相关属性
        // consumer.setPullBatchSize(16);
    }

}
